/**
 * 创建人：王曙光
 * 创建时间：2011-9-10
 * 功能描述：程序主界面展现及功能控制
 */
var _usercarelist = null;
var _diarylist = null;
var _namecardtimeout = 0;
$(function() {
	//启用拖拽
	Common.DragStart($(".main_header")[0]);
	//最小化和关闭
	$(".min").bind("click", function(event) {
		event.stopPropagation();
		appMin();
	});
	$(".close").bind("click", function(event) {
		event.stopPropagation();
		var configinfo = App.getConfig();
		if(configinfo.Close == 0) {
			appMin();
		} else {
			appClose();
		}
	});
	//系统托盘，托盘菜单
	var iconLoadComplete = function(event) {
		air.NativeApplication.nativeApplication.icon.bitmaps = [event.target.content.bitmapData];
	}
	air.NativeApplication.nativeApplication.autoExit = false;
	var iconLoad = new air.Loader();
	var iconMenu = createIconMenu();

	//还原
	air.NativeApplication.nativeApplication.icon.addEventListener("click", function() {
		air.NativeApplication.nativeApplication.icon.bitmaps = [];
		window.nativeWindow.visible = true;
	});
	air.NativeApplication.nativeApplication.icon.addEventListener(air.MouseEvent.RIGHT_CLICK, function(event) {
		var y = event.screenY - Const.menu._height;
		var x = event.screenX - Const.menu._width;
		Common.OpenMenu(x, y);
	});
	//最小化到系统托盘
	var appMin = function() {
		window.nativeWindow.visible = false;
		if(air.NativeApplication.supportsSystemTrayIcon) {
			air.NativeApplication.nativeApplication.autoExit = false;
			iconLoad.contentLoaderInfo.addEventListener(air.Event.COMPLETE, iconLoadComplete);
			iconLoad.load(new air.URLRequest("app:/assets/icons/AIRApp_16.png"));
			air.NativeApplication.nativeApplication.icon.tooltip = "C6桌面";
			//air.NativeApplication.nativeApplication.icon.menu = iconMenu;
		}
		if(air.NativeApplication.supportsDockIcon) {
			iconLoad.contentLoaderInfo.addEventListener(air.Event.COMPLETE, iconLoadComplete);
			iconLoad.load(new air.URLRequest("app:/assets/icons/AIRApp_128.png"));
			//air.NativeApplication.nativeApplication.icon.menu = iconMenu;
		}
	}
	/*********************************************************/
	//系统菜单
	$(".headPhoto").bind("mouseenter", function() {
		$(".menubar").show();
	});
	$(".headPhoto").bind("mouseleave", function() {
		$(".menubar").hide();
	});
	$(".menubar").bind("mouseup", function(event) {
		var popupMenu = createContextMenu();
		var y = event.pageY + window.nativeWindow.y;
		var x = event.pageX + window.nativeWindow.x;
		Common.OpenMenu(x, y);
		//popupMenu.display(window.nativeWindow.stage, event.clientX, event.clientY);
	});
	/********************************************************/
	//主功能区按钮，此处控制页面展示，无功能控制
	$(".main_header_line div[id]").bind("mouseup", function() {
		if(this.id == "wdiaryImg")
			return;
		if($(this).attr("status") == "0") {
			PageDown();
		} else {
			PageUp();
		}
		if($(this).attr("status") == '0') {
			$(".main_header_line div[id]").attr("status", "0");
			$(this).attr("status", "1");
		} else {
			$(".main_header_line div[id]").attr("status", "0");
			$(this).attr("status", "0");
			$(this).css("background-position", "0px 0px");
		}
	});
	/********************************************************/
	//组织架构加载
	$("#orgImg").bind("mouseup", function() {
		if(Const.main._cstatus == "u")
			return;

		//搜索提示
		$(".main_content_header").html("<div id='header_org_refresh'></div><input id='tbox_search' placeholder='输入姓名 回车搜索' />");

		//读取配置信息判断是否需要重新从网络获取组织架构信息
		var cacheInfo = App.getCacheInfo();
		var slice = 0;
		if(cacheInfo == null)
			slice = 0
		else
			slice = Math.round((new Date()).valueOf()) - Math.round(cacheInfo.org);
		if(slice == 0 || slice > Const.org._timeout) {
			//重新从网络获取
			ShowLoading();
			App.getUserList(function(data) {
				$(".main_content_scroll").html(data);
				$(".hnode").trigger("click");
			}, function(data) {
				HideLoading();
				Common.ShowTips(data);
			});
		} else {
			//直接读取缓存
			ShowLoading();
			App.getUserListFromCache(function(data) {
				$(".main_content_scroll").html(data);
				$(".hnode").trigger("click");
			});
		}
	});
	/*组织架构中的人员搜索*/
	$("#tbox_search").live("keydown", function(event) {
		//回车检测
		if(event.keyCode != 13)
			return;

		var tips = $(this).val().trim();
		App.getSearchData(tips, function(data) {
			//无论何时，先展开总部
			if(!$(".hnode").find("+.cnode").is(":visible")) {
				$(".hnode").trigger("click");
			}
			//p作为临时部门指针从栈顶往下移动
			var p = Math.round(data.pop());
			while(p === 0 || p === 1) {
				//0或者1表示不需要处理的部门
				p = Math.round(data.pop());
			}
			//从用户所在部门树中最顶层往下一次查找
			var obj = $(".hnode").find("+.cnode").find(">#dept_" + p.toString())[0];
			if(!$(obj).find("+.cnode").is(":visible"))
				$(obj).trigger("click");
			while(data.length > 0) {
				p = Math.round(data.pop());
				obj = $(obj).find("+.cnode").find(">.dnode[id='dept_" + p + "']");
				if(!$(obj).find("+.cnode").is(":visible"))
					$(obj).trigger("click");
			}
			if(!obj) {
				//直接不需要查找就在总部的用户
				obj = $(".hnode").find("+.cnode")[0];
			} else {
				//至少有两次结构的用户
				obj = $(obj).find("+.cnode")[0];
			}
			//页面内查找
			$(obj).find(".unode").each(function() {
				if($(this).html().indexOf(tips) > -1) {
					var offset = $(this).offset();
					var scrollLeft_ = $(".main_content_scroll")[0].scrollLeft;
					var scrollTop_ = $(".main_content_scroll")[0].scrollTop;
					$(".main_content_scroll").animate({
						scrollLeft : scrollLeft_ + offset.left
					}, 600);
					$(".main_content_scroll").animate({
						scrollTop : scrollTop_ + offset.top - 100
					}, 600);
					$(this).trigger("mouseenter");
				}
			});
		});
	});
	//隐藏名片卡
	$(".main_content_scroll").bind("mouseleave", function() {
		var win = Common.GetWin("namecard");
		if(win) {
			win.close();
		}
	});
	//组织架构样式
	InitOrg();
	/********************************************************/
	//关注人员，从本地加载
	$("#friImg").bind("mouseup", function() {
		if(Const.main._cstatus == "u")
			return;
		$(".main_content_header").html("");
		ShowLoading();
		App.getCareUserList(function(data, usercarelist) {
			$(".main_content_scroll").html(data);
			if(usercarelist != null) {
				_usercarelist = usercarelist;
			}
		});
	});
	$(".usercard_l").live("mouseenter", function() {
		if($(this).attr("flag") == "0") {
			$(this).css({
				"background" : "-webkit-gradient(linear,0 0,0 100%,from(#FDFDFD),to(#F3F3F3))"
			});
		}
	});
	$(".usercard_l").live("mouseleave", function() {
		if($(this).attr("flag") == "0") {
			$(this).css({
				"background" : "#fff"
			});
		}
	});
	$(".usercard_l").live("click", function() {
		$(".usercard_l").css({
			"background" : "#fff"
		});
		$(".usercard_l").attr("flag", "0");
		$(this).css({
			"background" : "-webkit-gradient(linear,0 0,0 100%,from(#F5F9FD),to(#C9E1F8))"
		});
		$(this).attr("flag", "1");
	});
	$(".usercard_l").live("dblclick", function() {
		Const.msg._targetid = $(this)[0].id;
		Common.OpenMsgWin();
	});
	$(".user_refresh").live("mouseenter", function() {
		$(this).css({
			"background-position-x" : "-100px"
		});
	});
	$(".user_refresh").live("mouseleave", function() {
		$(this).css({
			"background-position-x" : "-75px"
		});
	});
	$(".user_refresh").live("click", function() {
		event.stopPropagation();
		var obj = $(this).parent()[0];
		var uid = obj.id.split("_")[1];
		App.UpdateCareUserInfo(uid, function(data, flag) {
			if(flag == 1) {
				$(obj).find(".photoimg").attr("src", "assets/images/photos/" + uid + ".jpg");
			} else {
				$(obj).find(".photoimg").attr("src", "assets/images/head.gif");
			}
			$(obj).find("ul li").each(function(index) {
				switch(index) {
					case 0:
						$(this).html(data.userName);
						break;
					case 1:
						$(this).html(data.deptName);
						break;
					case 2:
						$(this).html(data.posiName);
						break;
					case 3:
						$(this).html(data.teleNum);
						break;
					case 4:
						$(this).html(data.userTel);
						break;
				}
			});
		});
	});
	/********************************************************/
	//工作日记
	$("#diaryImg").bind("mouseup", function() {
		if(Const.main._cstatus == "u")
			return;

		//直接从网络获取数据
		$(".main_content_header").html("");
		ShowLoading();
		App.getDiaryList(1, 20, function(dom, data) {
			var hstr = "";
			$(".main_content_scroll").html(dom);
			_diarylist = data.diarys;
			hstr += "<div id='header_diary_refresh'></div>"
			hstr += "<span class='funBtn' id=\"header_diary_20\">前20</span>";
			hstr += "<span class='funBtn' id=\"header_diary_40\">前40</span>";
			hstr += "<span class='funBtn' id=\"header_diary_100\">前100</span>";
			hstr += "<span class='funBtn' id=\"header_diary_400\">前400</span>";
			//hstr += "<span class='funBtn' id=\"header_diary_new\">写点什么？</span>";
			$(".main_content_header").html(hstr);
		}, function(err) {
			Common.ShowTips(err);
			HideLoading();
		});
	});
	//区分不同数量的日记请求
	$("#header_diary_20,#header_diary_40,#header_diary_100,#header_diary_400").live("click", function() {
		ShowLoading();
		App.getDiaryList(1, Math.round(this.id.split("_")[2]), function(dom, data) {
			$(".main_content_scroll").html(dom);
			_diarylist = data.diarys;
		}, function(err) {
			Common.ShowTips(err);
			HideLoading();
		});
	});
	//
	$(".diary_node").live("mouseenter", function() {
		if($(this).attr("flag") == "0") {
			$(this).css({
				"background" : "-webkit-gradient(linear,0 0,0 100%,from(#F9F9F9),to(#F3F3F3))"
			});
		}
	});
	$(".diary_node").live("mouseleave", function() {
		if($(this).attr("flag") == "0") {
			$(this).css({
				"background" : "#fff"
			});
		}
	});
	$(".diary_node").live("click", function() {
		$(".diary_node").css({
			"background" : "#fff"
		});
		$(".diary_node").attr("flag", "0");
		$(this).css({
			"background" : "-webkit-gradient(linear,0 0,0 100%,from(#EAF3FC),to(#C8E0F8))"
		});
		$(this).attr("flag", "1");
		var diary = _diarylist[Math.round($(this).attr("index"))];
		App.setTempData(JSON.stringify(diary));
		var x = window.nativeWindow.x + window.nativeWindow.width;
		var y = window.nativeWindow.y + 50;
		Common.OpenDiaryDetail(x, y);
	});
	//写日记
	$("#wdiaryImg").live("click", function() {
		Common.OpenDiaryNew();
	});
	$("#btnCancel").live("click", function() {
		$(".diary_new").slideUp(200);
	});
	/********************************************************/
	//未阅寻呼
	$("#msgImg").live("mouseup", function() {
		if(Const.main._cstatus == "u")
			return;
		$(".main_content_header").html("");
		ShowLoading();
		var callNum = 0;
		//网络加载未阅寻呼
		App.getUnreadMessageNum(function(data0) {
			callNum = Math.round(data0);
			//记录当前未阅寻呼真实数量，用于新寻呼提醒
			Const.main._msgcount = callNum;
			var totalNum = callNum % Const.main._pagesize == 0 ? parseInt(callNum / Const.main._pagesize) : parseInt(callNum / Const.main._pagesize) + 1;
			App.getCallNoSee(1, Const.main._pagesize, function(data1, next) {
				var hstr = "<div id='header_msg_refresh'></div><span id=\"header_msg_tips\">1/" + totalNum + "</span><div class='funBtn' id=\"header_msg_up\">◀</div><div class='funBtn' id=\"header_msg_down\">▶</div>";
				$(".main_content_header").html(hstr);
				$(".main_content_scroll").html(data1);
				RefreshTips();
			}, function(err1) {
				Common.ShowTips(err);
			});
		}, function(err0) {
			Common.ShowTips(err);
		});
	});
	$(".msg_from,.msg_replay").live("click", function() {

		Const.msg._targetid = "tid_" + $(this).attr("tid");
		//Const.send._send = "<span style='font-weight: bold'>" + $(this).html() + "</span>:<br/>" + $(this).parent().parent().find(".msg_body").html();
		Common.OpenMsgWin();
	});
	//设置已阅
	$(".msg_read").live("mouseup", function() {
		var tid = $(this).attr("tid");
		App.setMessageRead(tid, function() {
			$("#msg_" + tid).hide();
			//记录当前未阅寻呼真实数量，用于新寻呼提醒
			Const.main._msgcount = Const.main._msgcount - 1;
			if(Const.main._msgcount < 0)
				Const.main._msgcount = 0;
		}, function(data) {
			Common.ShowTips(data);
		})
	});
	$("#header_msg_up,#header_msg_down").live("mouseenter", function() {
		$(this).css({
			"background-position-x" : "-18px"
		});
	});
	$("#header_msg_up,#header_msg_down").live("mouseleave", function() {
		$(this).css({
			"background-position-x" : "0px"
		});
	});
	//上一页
	$("#header_msg_up").live("click", function() {
		var now = Math.round($("#header_msg_tips").html().split("/")[0]);
		var total = Math.round($("#header_msg_tips").html().split("/")[1]);
		if(now === 1)
			return;
		ShowLoading();
		App.getCallNoSee(now - 1, Const.main._pagesize, function(data1, next) {
			$("#header_msg_tips").html((now - 1) + "/" + total);
			$(".main_content_scroll").html(data1);
			RefreshTips();
		}, function(err1) {
			Common.ShowTips(err);
			HideLoading();
		});
	});
	//下一页
	$("#header_msg_down").live("click", function() {
		var now = Math.round($("#header_msg_tips").html().split("/")[0]);
		var total = Math.round($("#header_msg_tips").html().split("/")[1]);
		if(now === total)
			return;
		ShowLoading();
		App.getCallNoSee(now + 1, Const.main._pagesize, function(data1, next) {
			$("#header_msg_tips").html((now + 1) + "/" + total);
			$(".main_content_scroll").html(data1);
			RefreshTips();
		}, function(err1) {
			Common.ShowTips(err);
			HideLoading();
		});
	});
	//刷新按钮样式
	$("#header_msg_refresh,#header_org_refresh,#header_diary_refresh").live("mouseenter", function() {
		$(this).css({
			"background-position-x" : "-25px"
		});
	});
	$("#header_msg_refresh,#header_org_refresh,#header_diary_refresh").live("mouseleave", function() {
		$(this).css({
			"background-position-x" : "0px"
		});
	});
	$("#header_msg_refresh,#header_org_refresh,#header_diary_refresh").live("mousedown", function() {
		$(this).css({
			"background-position-x" : "-50px"
		});
	});
	$("#header_msg_refresh,#header_org_refresh,#header_diary_refresh").live("mouseup", function() {
		$(this).css({
			"background-position-x" : "0px"
		});
	});
	//寻呼刷新
	$("#header_msg_refresh").live("click", function() {
		ShowLoading();
		var callNum = 0;
		App.getUnreadMessageNum(function(data0) {
			callNum = Math.round(data0);
			Const.main._msgcount = callNum;
			var totalNum = callNum % Const.main._pagesize == 0 ? parseInt(callNum / Const.main._pagesize) : parseInt(callNum / Const.main._pagesize) + 1;
			App.getCallNoSee(1, Const.main._pagesize, function(data1, next) {
				var hstr = "<div id='header_msg_refresh'></div><span id=\"header_msg_tips\">1/" + totalNum + "</span><div  class='funBtn' id=\"header_msg_up\">◀</div><div  class='funBtn' id=\"header_msg_down\">▶</div>";
				$(".main_content_header").html(hstr);
				$(".main_content_scroll").html(data1);
				RefreshTips();
			}, function(err1) {
				Common.ShowTips(err);
			});
		}, function(err0) {
			Common.ShowTips(err);
		});
	});
	//组织架构刷新
	$("#header_org_refresh").live("click", function() {
		ShowLoading();
		App.getUserList(function(data) {
			$(".main_content_scroll").html(data);
			$(".hnode").trigger("click");
		}, function(data) {
			HideLoading();
			Common.ShowTips(data);
		});
	});
	//日记刷新
	$("#header_diary_refresh").live("click", function() {
		//直接从网络获取数据
		$(".main_content_header").html("");
		ShowLoading();
		App.getDiaryList(1, 20, function(data, next) {
			var hstr = "";
			$(".main_content_scroll").html(data);
			hstr += "<div id='header_diary_refresh'></div>"
			hstr += "<span class='funBtn' id=\"header_diary_20\">前20</span>";
			hstr += "<span class='funBtn' id=\"header_diary_40\">前40</span>";
			hstr += "<span class='funBtn' id=\"header_diary_100\">前100</span>";
			hstr += "<span class='funBtn' id=\"header_diary_400\">前400</span>";
			//hstr += "<span class='funBtn' id=\"header_diary_new\">写点什么？</span>";
			$(".main_content_header").html(hstr);
		}, function(err) {
			Common.ShowTips(err);
			HideLoading();
		});
	});
	//寻呼附件下载
	$(".msg_attachment a,.diary_attachment a").live("click", function() {
		var fileId = this.id.split("_")[1];
		var directory = air.File.documentsDirectory;
		var fileName = $(this).html().trim();
		var fext = $(this).html().split(".")[$(this).html().split(".").length - 1];
		directory.addEventListener(air.Event.SELECT, function() {
			Const.download._filePath = directory.nativePath + "\\" + fileName;
			Const.download._fileId = fileId;
			Common.OpenDownloadWin();
		});
		directory.browseForDirectory(fext);
	});
	/********************************************************/
	//加关注
	$(".user_add").live("mouseenter", function() {
		$(this).css({
			"background-position" : "-12px 0px"
		});
	});
	$(".user_add").live("mouseleave", function() {
		$(this).css({
			"background-position" : "0px 0px"
		});
	});
	$(".user_add").live("click", function() {
		$(this).parent().hide();
		if($(this).html() == "+") {
			$(this).html("-");
		} else {
			$(this).html("+");
		}
		//增加取消关注
		var index = Math.round($(this).attr("flag"));
		App.CareUser(_usercarelist[index]);
	});
	/********************************************************/
	//底部按钮
	$(".to_top").bind("mouseup", function() {
		$(".main_header_line").find("div[id][flag='1']").trigger("mousedown");
		$(".main_header_line").find("div[id][flag='1']").trigger("mouseup");
	});
	/********************************************************/
	//改变大小
	$(".to_resize").bind("mousedown", function() {
		Const.main._isresize = 1;
		Const.main._wtheight = window.nativeWindow.height;
		window.nativeWindow.startResize("BR");
	});
	/********************************************************/
	//调整窗口大小时处理界面
	$(window).resize(function() {
		if(Const.main._isresize == 0)
			return;
		var nwHeight = window.nativeWindow.height;
		Const.main._cheight = Const.main._cheight + nwHeight - Const.main._wtheight;
		$(".main_content_scroll").css({
			"height" : (Const.main._cheight - Const.main._cheader_height - Const.main._cheader_food) + "px"
		});
		Const.main._isresize = 0;
	});
	/********************************************************/
	//初始化登录者信息
	var configinfo = App.getConfig();
	//上次未阅寻呼
	Const.main._msgcount = Math.round(configinfo.CallNum);
	//个人信息
	App.getUserInfo(configinfo.LoginCode, function(data) {
		var userTips = data.userName + "&nbsp;&nbsp;" + data.posiName;
		$(".title").html(userTips);
		if(data.photoCode == null || data.photoCode == "") {
		} else {
			//个人头像
			var file = new air.File(air.File.applicationDirectory.resolvePath("app:/assets/images/photos/" + configinfo.LoginCode + ".jpg").nativePath);
			var byteData = new air.ByteArray();
			Base64.decode(data.photoCode, byteData);
			var stream = new air.FileStream();
			stream.open(file, air.FileMode.WRITE);
			stream.writeBytes(byteData, 0, byteData.length);
			stream.close();
			$(".photoimg").attr("src", "assets/images/photos/" + configinfo.LoginCode + ".jpg");
		}
	}, function(data) {
		Common.ShowTips(data);
	});
	/********************************************************/
	//寻呼提醒
	setInterval(function() {
		App.getUnreadMessageNum(function(data) {
			//检测是否有新的寻呼
			var subNum = Math.round(data) - Const.main._msgcount;
			if(subNum > 0) {
				if(subNum !== Const.main._msgsubcount) {
					Const.main._msgsubcount = subNum;
					//
					//Const.main._msgcount = Math.round(data);
					//面板提醒，默认显示，无需配置
					if(subNum >= 10) {
						$(".tip_num").html("N");
					} else {
						$(".tip_num").html(subNum.toString());
					}
					$(".tip_num").show();

					//声音提醒
					var config = App.getConfig();
					if(config.PlaySound == 1) {
						var soundPath = new air.URLRequest("app:/assets/wav/msg.mp3");
						var s = new air.Sound();
						s.load(soundPath);
						s.play();
					}
					//pop弹出提醒
					if(config.Pop == 1) {
						App.getLastCallNoSee(function(data) {
							Const.pop._from = data.messages[0].sender;
							Const.pop._msg = data.messages[0].content;
							Const.pop._msgid = data.messages[0].messageid;
							var currentScreen = Common.GetCurrentScreen();
							var x = currentScreen.bounds.width - Const.pop._width;
							var y = currentScreen.bounds.height - Const.pop._height;
							Common.PopWin(x - 20, y - 40);
						});
					}
				}
			}
		}, function() {

		});
	}, Const.main._timeout);
});
//页面展开
function PageDown() {
	//已经展开的页面不再处理
	if(Const.main._cstatus == "d")
		return;
	//展开窗口
	window.nativeWindow.height = window.nativeWindow.height + Const.main._cheight;
	//展开页面
	$(".main_content_scroll").animate({
		"height" : (Const.main._cheight - Const.main._cheader_height - Const.main._cheader_food) + "px"
	}, 200);
	//头部
	$(".main_content_header").show();
	//尾部
	$(".main_content_food").show();
	//设定窗口最小值
	window.nativeWindow.minSize = new air.Point(Const.main._minSizeX_d, Const.main._minSizeY_d);
	//去掉结合处的圆角
	$(".main_header").css({
		"-webkit-border-bottom-left-radius" : "0px",
		"-webkit-border-bottom-right-radius" : "0px"
	});
	//标记当前页面的状态
	Const.main._cstatus = "d";
}

//页面收起
function PageUp() {
	//已经收起的页面不再处理
	if(Const.main._cstatus == "u")
		return;
	//隐藏头尾
	$(".main_content_header").hide();
	$(".main_content_food").hide();
	//收起内容
	$(".main_content_scroll").animate({
		"height" : "0px"
	}, 200, function() {
		window.nativeWindow.height = window.nativeWindow.height - Const.main._cheight;
	});
	//调整窗口最小值
	window.nativeWindow.minSize = new air.Point(Const.main._minSizeX_u, Const.main._minSizeY_u);
	//结合处的圆角
	$(".main_header").css({
		"-webkit-border-bottom-left-radius" : "2px",
		"-webkit-border-bottom-right-radius" : "2px"
	});
	//标记状态
	Const.main._cstatus = "u";
}

//组织架构显示样式
function InitOrg() {
	//样式
	$(".hnode,.dnode,.unode").live("mouseenter", function() {
		if($(this)[0].id == Const.org._nodeid)
			return;
		$(this).css({
			"background-color" : "#EEEEEE"
		});
	});
	//树节点移开鼠标还原样式
	$(".hnode,.dnode,.unode").live("mouseleave", function() {
		if($(this)[0].id == Const.org._nodeid)
			return;
		$(this).css({
			"background-color" : "#fff"
		});
	});
	//双击打开寻呼回复页面
	$(".hnode,.dnode,.unode").live("dblclick", function() {
		isdb = true;
		Const.msg._targetid = $(this)[0].id;
		Common.OpenMsgWin();
	});
	//显示人员名片
	$(".unode").live("click", function(event) {
		isdb = false;
		var id = this.id.split("_")[1];
		window.setTimeout(function() {
			if(isdb != false)
				return;
			App.setTempData(id);
			var y = event.pageY + window.nativeWindow.y - 60;
			var x = window.nativeWindow.x - 270;
			Common.OpenNameCard(x, y + 10);
		}, 500);
	});
	//展开收起树节点
	$(".hnode,.dnode,.unode").live("click", function() {
		var obj = this;
		$("#" + Const.org._nodeid).css({
			"background-color" : "#EEEEEE",
			"font-weight" : "normal",
			"background-color" : "#fff"
		})
		$(obj).css({
			"background-color" : "#D9E8FB",
			"font-weight" : "bold"
		});
		Const.org._nodeid = $(obj)[0].id;
		if($(obj).attr("flag") == "0") {
			$(obj).find("+.cnode").hide();
			$(obj).attr("flag", "1");
			$(obj).html($(obj).attr("dept"));
		} else {
			if($(obj)[0].id.split("_")[0] == "dept") {
				if($(obj).html().indexOf('******') < 0) {
					if($(obj).find("+.cnode").length == 0) {
						$(obj).after(App.getChildUserList($(obj)[0].id.split("_")[1]));
					}
					$(obj).find("+.cnode").show();
					var onlineNum = $(obj).find("+.cnode").find("div[status='online']").length;
					var offlineNum = $(obj).find("+.cnode").find("div[status='offline']").length;
					$(obj).html($(obj).attr("dept") + "(" + onlineNum + "/" + (offlineNum + onlineNum) + ")");
				}
			}
			$(obj).attr("flag", "0");
		}
	});
}

//显示加载进度
function ShowLoading() {
	$(".main_content_scroll").html("<div style=\"width: 100%;height: 100%;background-image: url(assets/images/main_loading.gif); background-position: center,center;background-repeat: no-repeat;\"></div>");
}

//隐藏加载进度
function HideLoading() {
	$(".main_content_scroll").html("");
}

//重置未阅计数
function RefreshTips() {
	$(".tip_num").hide();
	Const.main._msgsubcount = 0;
}

//系统自动更新
var appUpdater = null;
appUpdater = new air.ApplicationUpdaterUI();
appUpdater.configurationFile = new air.File("app:/config/update-config.xml");
appUpdater.addEventListener(air.ErrorEvent.ERROR, function(event) {
	Common.ShowTips(event.toString());
});
appUpdater.addEventListener(air.UpdateEvent.BEFORE_INSTALL, function(event) {
	//安装前备份应用程序配置
	App.backupToXML();
});

appUpdater.initialize();

//程序是否是第一次运行,从备份数据恢复
if(Common.IsFirstRun()) {
	App.recoverFromXML();
}
function createIconMenu() {
	var iconMenu = new air.NativeMenu();
	//检测更新
	var updateCommand = iconMenu.addItem(new air.NativeMenuItem("检测更新"));
	updateCommand.addEventListener(air.Event.SELECT, function(event) {
		appUpdater.checkNow();
	});
	//单点登录进入系统
	var loginC6Command = iconMenu.addItem(new air.NativeMenuItem("进入平台"));
	loginC6Command.addEventListener(air.Event.SELECT, function(event) {
		var config = App.getConfig();
		var c6url = config.WsURL.replace("JHSoft.Ws/jhwsforapp.asmx", "JHSoft.Web.ssoc6/LoginByURLNP.aspx?");
		c6url += base64encode("userid=" + config.LoginCode + "&password=" + config.Password);
		var urlReq = new air.URLRequest(c6url);
		air.navigateToURL(urlReq);
	});
	//窗体始终在前
	var configinfo = App.getConfig();
	var alwaysInFront = null;
	var alwaysInFrontItem = new air.NativeMenuItem("总在最前");
	if(configinfo.AlwaysInFront == 1) {
		alwaysInFrontItem.checked = true;
	} else {
		alwaysInFrontItem.checked = false;
	}
	alwaysInFront = iconMenu.addItem(alwaysInFrontItem);
	alwaysInFront.addEventListener(air.Event.SELECT, function() {
		if(configinfo.AlwaysInFront == 1) {
			window.nativeWindow.alwaysInFront = false;
			configinfo.AlwaysInFront = 0;
			alwaysInFrontItem.checked = false;

		} else {
			window.nativeWindow.alwaysInFront = true;
			configinfo.AlwaysInFront = 1;
			alwaysInFrontItem.checked = true;
		}
		App.setConfig(configinfo);
	});
	//注销
	var leaveCommand = iconMenu.addItem(new air.NativeMenuItem("切换用户"));
	leaveCommand.addEventListener(air.Event.SELECT, function(event) {
		air.NativeApplication.nativeApplication.icon.bitmaps = [];
		Common.OpenLoginWin();
	});
	//退出
	var exitCommand = iconMenu.addItem(new air.NativeMenuItem("退出桌面"));
	exitCommand.addEventListener(air.Event.SELECT, function(event) {
		appClose();
	});
	return iconMenu;
}

//创建上下文菜单，系统主菜单
function createContextMenu() {
	var menu = new air.NativeMenu();
	//检测更新
	var updateCommand = menu.addItem(new air.NativeMenuItem("检测更新"));
	updateCommand.addEventListener(air.Event.SELECT, function(event) {
		appUpdater.checkNow();
	});
	//单点登录进入系统
	var enterC6 = menu.addItem(new air.NativeMenuItem("进入平台"));
	enterC6.addEventListener(air.Event.SELECT, function() {
		var config = App.getConfig();
		var c6url = config.WsURL.replace("JHSoft.Ws/jhwsforapp.asmx", "JHSoft.Web.ssoc6/LoginByURLNP.aspx?");
		c6url += base64encode("userid=" + config.LoginCode + "&password=" + config.Password);
		var urlReq = new air.URLRequest(c6url);
		air.navigateToURL(urlReq);
	});
	//窗体始终在前
	var configinfo = App.getConfig();
	var alwaysInFront = null;
	var alwaysInFrontItem = new air.NativeMenuItem("总在最前");
	if(configinfo.AlwaysInFront == 1) {
		alwaysInFrontItem.checked = true;
	} else {
		alwaysInFrontItem.checked = false;
	}
	alwaysInFront = menu.addItem(alwaysInFrontItem);
	alwaysInFront.addEventListener(air.Event.SELECT, function() {
		if(configinfo.AlwaysInFront == 1) {
			window.nativeWindow.alwaysInFront = false;
			configinfo.AlwaysInFront = 0;
			alwaysInFrontItem.checked = false;

		} else {
			window.nativeWindow.alwaysInFront = true;
			configinfo.AlwaysInFront = 1;
			alwaysInFrontItem.checked = true;
		}
		App.setConfig(configinfo);
	});
	//注销当前用户
	var changeUser = menu.addItem(new air.NativeMenuItem("切换用户"));
	changeUser.addEventListener(air.Event.SELECT, function() {
		Common.OpenLoginWin();
	});
	//退出软件
	var existApp = menu.addItem(new air.NativeMenuItem("退出桌面"));
	existApp.addEventListener(air.Event.SELECT, function() {
		var configinfo = App.getConfig();
		if(configinfo.Close == 0) {
			appMin();
		} else {
			appClose();
		}
	});
	return menu;
}

//保存信息退出应用程序
function appClose() {
	var Config = Common.GetEmptyConfig();
	Config.WinStartX = window.nativeWindow.x.toString();
	Config.WinStartY = window.nativeWindow.y.toString();
	Config.WinWidth = window.nativeWindow.width.toString();
	Config.WinHeight = Const.main._cheight.toString();
	Config.CallNum = Const.main._msgcount;
	App.setConfig(Config);
	air.NativeApplication.nativeApplication.icon.bitmaps = [];
	air.NativeApplication.nativeApplication.exit();
}